using Flurl;
using Flurl.Http;
using Microsoft.Owin;
using Newtonsoft.Json;
using Polly;
using Polly.Caching;
using System;
using System.Runtime.Caching;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web.Http;

namespace IP.Hash
{
    public class HomeController : BaseController
    {
        [HttpGet]
        public async Task<IHttpActionResult> GetIp()
        {
            var owinContext = (OwinContext)Request.Properties["MS_OwinContext"];
            string ipaddress = owinContext.Request.RemoteIpAddress;
            Log.Info(string.Format("GetIp.ipaddress=={0}", ipaddress));
            var lang = "en";
            //Policy
            var retryTwoTimesPolicy = Policy.Handle<Exception>().RetryAsync(2);
            var online = await retryTwoTimesPolicy.ExecuteAsync(() => PcOnline.SetQueryParam("ip", ipaddress).GetStringAsync());
            if (!string.IsNullOrEmpty(online))
            {
                var pc = Regex.Match(online, "{\"([\\s\\S]*?)\"}");
                if (pc.Groups.Count > 0)
                {
                    var result = JsonConvert.DeserializeObject<pconline>(pc.Groups[0].ToString());
                    if (result != null && !result.proCode.Equals("0")) lang = "en";
                }
            }
            var json = ConfigUtility<dynamic>.JsonConfig(IoHelper.GetMapPath(string.Format("/config/config_{0}.json", lang)));
            return Json(json);
        }

        /// <summary>
        /// 缓存 处理 IP
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IHttpActionResult> GetJson()
        {
            var owinContext = (OwinContext)Request.Properties["MS_OwinContext"];
            var xfr = owinContext.Request.Headers.GetValues("X-FORWARDED-FOR");
            Log.Info(string.Format("GetIp.X-FORWARDED-FOR=={0}", xfr));
            string ipaddress = owinContext.Request.RemoteIpAddress;
            Log.Info(string.Format("GetIp.ipaddress=={0}", ipaddress));
            var lang = "en";
            //Policy
            var cachePolicy = Policy.CacheAsync(new Polly.Caching.MemoryCache.MemoryCacheProvider(MemoryCache.Default), TimeSpan.FromHours(2));
            var online = await cachePolicy.ExecuteAsync(() => PcOnline.SetQueryParam("ip", ipaddress).GetStringAsync(), new Context(string.Format("client_request_ip_address_{0}", ipaddress)));
            if (!string.IsNullOrEmpty(online))
            {
                var pc = Regex.Match(online, "{\"([\\s\\S]*?)\"}");
                if (pc.Groups.Count > 0)
                {
                    var result = JsonConvert.DeserializeObject<pconline>(pc.Groups[0].ToString());
                    if (result != null && !result.proCode.Equals("0")) lang = "en";
                }
            }
            var json = ConfigUtility<dynamic>.JsonConfig(IoHelper.GetMapPath(string.Format("/config/config_{0}.json", lang)));
            return Json(json);
        }
    }
}
